$(document).ready(function() {
    let page = 1;
    let size = 5;
    let classesData = [];
    let currentName = "";
    let currentID = "";

    // 显示加载动画
    function showLoading() {
        $("#loadingSpinner").css("display", "flex").hide().fadeIn(300);
    }

    // 隐藏加载动画
    function hideLoading() {
        $("#loadingSpinner").fadeOut(300);
    }

    // 加载班级数据
    function loadClasses(page, size, name = "", id = "") {
        showLoading();
        $.ajax({
            url: "/attend_war/instructor/classes",
            method: "GET",
            dataType: "json",
            data: { page, size, name, id },
            success: function(data) {
                classesData = data;
                let tableContent = "";

                data.forEach(classItem => {
                    tableContent += `
                        <tr class="animate__animated animate__fadeIn">
                            <td>${classItem.classID}</td>
                            <td>${classItem.className}</td>
                            <td>${classItem.depID}</td>
                            <td>${classItem.major}</td>
                            <td>${classItem.grade}</td>
                            <td>
                                <button class="btn-primary edit-btn" data-id="${classItem.classID}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn-danger delete-btn" data-id="${classItem.classID}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });

                $("#classTable tbody").html(tableContent);
                $("#currentPage").text(page);
                updateStats(data);
            },
            error: function(jqXHR, textStatus) {
                alert("获取班级数据失败: " + textStatus, 'error');
            },
            complete: hideLoading
        });
    }

    // 更新统计数据
    function updateStats(data) {
        $("#totalClasses").text(data.length);
        const departments = new Set(data.map(item => item.depID));
        $("#totalDepartments").text(departments.size);
        const majors = new Set(data.map(item => item.major));
        $("#totalMajors").text(majors.size);
    }

    // 搜索功能
    let searchTimeout;
    $("#searchBtn").click(function() {
        clearTimeout(searchTimeout);
        currentName = $("#searchName").val();
        currentID = $("#searchID").val();
        page = 1;
        loadClasses(page, size, currentName, currentID);
    });

    // 添加班级
    $("#addClassBtn").click(function() {
        $("#modalTitle").text("添加班级信息");
        $("#editClassID, #editClassName, #editDepID, #editMajor, #editGrade").val("");
        $("#editModal").data('original-id', null);
        $("#editModal").fadeIn(300);
        $(".modal-content").addClass("animate__animated animate__slideInDown");
    });

    // 编辑班级
    $(document).on('click', '.edit-btn', function() {
        const classID = $(this).data('id');
        const classItem = classesData.find(c => c.classID === classID);

        if (classItem) {
            $("#editClassID").val(classItem.classID);
            $("#editClassName").val(classItem.className);
            $("#editDepID").val(classItem.depID);
            $("#editMajor").val(classItem.major);
            $("#editGrade").val(classItem.grade);
            $("#editModal").data('original-id', classID);
            $("#modalTitle").text("编辑班级信息");
            $("#editModal").fadeIn(300);
            $(".modal-content").addClass("animate__animated animate__slideInDown");
        }
    });

    // 保存更改
    $("#saveChanges").click(function() {
        const originalID = $("#editModal").data('original-id');
        const classData = {
            id: originalID,
            classID: $("#editClassID").val(),
            className: $("#editClassName").val(),
            depID: $("#editDepID").val(),
            major: $("#editMajor").val(),
            grade: $("#editGrade").val()
        };

        showLoading();
        $.ajax({
            url: "/attend_war/instructor/classes",
            method: originalID ? "PUT" : "POST",
            contentType: "application/json",
            data: JSON.stringify(classData),
            success: function() {
                alert(originalID ? "修改成功" : "添加成功");
                $("#editModal").fadeOut(300);
                loadClasses(page, size, currentName, currentID);
            },
            error: function() {
                alert(originalID ? "修改失败" : "添加失败", 'error');
            },
            complete: hideLoading
        });
    });

    // 删除班级
    $(document).on('click', '.delete-btn', function() {
        const classID = $(this).data('id');
        if (confirm("确定要删除该班级吗？")) {
            showLoading();
            $.ajax({
                url: "/attend_war/instructor/classes?classID=" + classID,
                method: "DELETE",
                success: function() {
                    alert("删除成功");
                    loadClasses(page, size, currentName, currentID);
                },
                error: function(xhr) {
                    alert(xhr.responseText || "删除失败", 'error');
                },
                complete: hideLoading
            });
        }
    });

    // 分页控制
    $("#prevPage").click(function() {
        if (page > 1) {
            page--;
            loadClasses(page, size, currentName, currentID);
        }
    });

    $("#nextPage").click(function() {
        page++;
        loadClasses(page, size, currentName, currentID);
    });

    // 关闭模态框
    $("#closeModal, #cancelEdit").click(function() {
        $("#editModal").fadeOut(300);
    });

    // 点击模态框外部关闭
    $(window).click(function(event) {
        if ($(event.target).is("#editModal")) {
            $("#editModal").fadeOut(300);
        }
    });

    // 初始加载
    loadClasses(page, size);
});